package com.mysteel.ware.listener;

import com.mysteel.common.to.mq.OrderTo;
import com.mysteel.common.to.mq.StockLockedTo;
import com.mysteel.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * ProjectName: mail
 * ClassName: WareStockReleaseListener
 * Description:
 * date: 2021/03/31/031 9:26
 *
 * @author xiaochao
 */
@Slf4j
@Service
@RabbitListener(queues = {"stock.release.stock.queue"})
public class WareStockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void releaseLockedStock(StockLockedTo stockLockedTo, Message message, Channel channel){
        try {
            wareSkuService.handleStockLockedRelease(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException e1) {
                log.error("库存解锁失败，消息重新入队...");
            }
        }
    }

    @RabbitHandler
    public void handlerOrderClose(OrderTo orderTo,Message message,Channel channel){
        log.info("订单关闭:{}，准备解锁库存...",orderTo.getOrderSn());
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException e1) {
                log.error("库存解锁失败，消息重新入队...");
            }
        }
    }
}
